<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<button id="creatConnect">创建SSE连接</button>
	<button id="buildSubmit">开始服务端消息推送</button>
	<button id="closeBtn">关闭连接</button>
	<pre><code id="app"></code></pre>
	<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
	<script>
		let SSE = null
		const actionApi = (url, params = {}) => {
			return new Promise((resolve, reject) => {
				$.ajax({
					url: `http://127.0.0.1:3000/api/${url}`,
					method: 'post',
					data: params,
					// 成功回调
					success: res => {
						resolve(res)
					},
					error: err => {
						reject(err)
					}
				})
			})
		}
		creatConnect.onclick = () => {
			// 通过 new EventSource 开启 SSE
			SSE = new EventSource(`http://127.0.0.1:3000/api/push`);
			// 监听 message 事件
			SSE.onmessage = event => {
				// 挂到载体上面
				app.innerHTML += `${event.data} \n`
			}
			SSE.onerror = (err) => {
				console.error(err)
			}
			SSE.onopen = () => {
				console.log('SSE连接成功\n可以开始消息推送了')
			}
		}

		buildSubmit.onclick = () => {
			// 构建之前清空载体
			app.innerHTML = '';
			// 发起请求
			actionApi('connect').then(res => {
				console.log(res.msg)
			})
		}

		closeBtn.onclick = () => {
			SSE.close()
			actionApi('close')
		}
	</script>
</body>

</html>